package com.ruoyi.system.service.vantservice.shopservice.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.RandomUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.construction.RentalService;
import com.ruoyi.system.domain.construction.Team;
import com.ruoyi.system.domain.supe.PlatformCoupon;
import com.ruoyi.system.domain.vo.ApiBuildingVo;
import com.ruoyi.system.domain.zhuangxiumain.orderformMain.OrderDetail;
import com.ruoyi.system.domain.zhuangxiumain.shopMain.*;
import com.ruoyi.system.domain.zhuangxiumain.vo.PpiUrlVo;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.vant.shop.ApiProductInfoMapper;
import com.ruoyi.system.mapper.zhuangxiumapper.shopMapper.ProductInfoMapper;
import com.ruoyi.system.mapper.zhuangxiumapper.shopMapper.ProductPicInfoMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.vantservice.shopservice.ApiProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;


@Service
public class ApiProductInfoServiceImpl implements ApiProductInfoService {

    @Autowired(required = false)
    private ApiProductInfoMapper apiProductInfoMapper;

    @Autowired
    private ISysUserService userService;

    @Override
    public List<ProductInfo> findAllList(ProductInfo productInfo) {
        if (!StringUtils.isNull(productInfo)) {
            if (productInfo.getAddress() == null && "".equals(productInfo.getAddress())) productInfo.setAddress("不查询");
        }else {
            productInfo.setAddress("不查询");
        }
        return apiProductInfoMapper.findAllList(productInfo);
    }

    @Override
    public List<ApiBuildingVo> findConstructionList(ApiBuildingVo apiBuildingVo) {
        if (!StringUtils.isNull(apiBuildingVo)) {
            if (apiBuildingVo.getAddress() == null && "".equals(apiBuildingVo.getAddress())) apiBuildingVo.setAddress("不查询");
        }
        return apiProductInfoMapper.findConstructionList(apiBuildingVo);
    }

    @Override
    public List<ProductInfo> findAllAdder(String address) {
        return apiProductInfoMapper.findAllAdder(address);
    }

    @Override
    public ProductInfo selectProductInfoById(Integer productId) {
        return apiProductInfoMapper.selectProductInfoById(productId);
    }

    @Override
    public List<ProductInfo> selectProductInfoList(ProductInfo productInfo) {
        return apiProductInfoMapper.selectProductInfoList(productInfo);
    }

    /**
     * 查询商品分类列表
     * @return
     */
    public List<ProductCategory> selectProductCategories(String categoryType){
        return apiProductInfoMapper.selectProductCategories(categoryType);
    }

    /**
     * 查询商品类别下的商品信息
     * @param cateGoryId
     * @return
     */
    public List<ProductInfo> selectProductByCateGory(Long cateGoryId){
        // 创建集合储存分类ID
        List<Long> categoryIds = new ArrayList<Long>();
        // 根据一级分类ID查询二级分类ID
        List<ProductCategory> productCategoryList = apiProductInfoMapper.selectCategoriesByParentId(cateGoryId);
        for (ProductCategory productCategory : productCategoryList) {
            categoryIds.add(Long.valueOf(productCategory.getCategoryId()));
        }
        categoryIds.add(cateGoryId);
        return apiProductInfoMapper.selectProductByCateGory(categoryIds);
    }

    @Override
    public List<ProductInfo> selectProductByCateGoryOne(ProductInfo productInfo) {
        // 创建集合储存分类ID
        List<Long> categoryIds = new ArrayList<Long>();
        // 根据一级分类ID查询二级分类ID

        String a = productInfo.getA();
        String address = productInfo.getAddress();
        System.err.println();
        List<ProductCategory> productCategoryList = apiProductInfoMapper.selectCategoriesByParentId(Long.valueOf(productInfo.getA()));
        for (ProductCategory productCategory : productCategoryList) {
            categoryIds.add(Long.valueOf(productCategory.getCategoryId()));
        }
        categoryIds.add(Long.valueOf(productInfo.getA()));
        return apiProductInfoMapper.selectProductByCateGoryOne(categoryIds,address);
    }

    @Override
    public int xiaoliang(Long productId) {
        return apiProductInfoMapper.xiaoliang(productId);
    }


    /**
     * 根据一级类别ID查询二级类别列表
     * @param cateGoryId
     * @return
     */
    public List<ProductCategory> selectSecondCategories(Long cateGoryId){
        return apiProductInfoMapper.selectSecondCategories(cateGoryId);
    }

    /**
     * 查询商品类别下的商品信息
     * @param cateGoryId
     * @return
     */
    public List<ProductInfo> getProductByCateGory(Long cateGoryId){
        // 创建集合储存分类ID
        List<Long> categoryIds = new ArrayList<Long>();
        categoryIds.add(cateGoryId);
        return apiProductInfoMapper.selectProductByCateGory(categoryIds);
    }

    @Override
    public List<ProductInfo> CateGoryName(String categoryName) {
        // 创建集合储存分类ID
        List<String> categoryNames = new ArrayList<String>();
        categoryNames.add(categoryName);
        return apiProductInfoMapper.CateGoryName(categoryNames);
    }

    @Override
    public List<ProductInfo> selectProductByCateGoryTypeOne(String address) {
        return apiProductInfoMapper.selectProductByCateGoryTypeOne(address);
    }

    @Override
    public List<ProductInfo> selectProductByCateGoryTypeTwo(String address) {
        return apiProductInfoMapper.selectProductByCateGoryTypeTwo(address);
    }


    /**
     * 根据商品ID查询商品信息
     * @param productId
     * @return
     */
    public ProductInfo getProductById(Long productId){
        return apiProductInfoMapper.getProductById(productId);
    }

    /**
     * 根据品类类别查询商品列表
     * @param categoryType
     * @return
     */
    public List<ProductInfo> selectProductByCateGoryType(String categoryType){
        return apiProductInfoMapper.selectProductByCateGoryType(categoryType);
    }

    /**
     * 根据供应商ID查询供应商信息
     * @param supplierId
     * @return
     */
    public Map<String, Object> getSupplierById(Long supplierId){
        // 返回Map集合
        Map<String, Object> map = new HashMap<String, Object>();
        // 成交量
        int count = 0;
        // 成交额
        Double turnover = 0.0;
        // 商品ID集合
        List<Integer> infoIds = new ArrayList<Integer>();
        // 店铺下的商品集合
        List<ProductInfo> productInfoList = this.selectProductBySupplierId(supplierId);
        for (ProductInfo productInfo : productInfoList) {
            infoIds.add(productInfo.getProductId());
        }
        List<OrderDetail> orderDetailList = this.apiProductInfoMapper.selectOrderDetailByProIds(infoIds);
        for (OrderDetail orderDetail : orderDetailList) {
            count += orderDetail.getProductCnt();
            turnover += (orderDetail.getProductCnt()*orderDetail.getProductPrice());
        }
        map.put("count",count);
        map.put("turnover",turnover);
        map.put("supplier",apiProductInfoMapper.getSupplierById(supplierId));
        return map;
    }

    /**
     * 根据供应商ID查询商品信息
     * @param supplierId
     * @return
     */
    public List<ProductInfo> selectProductBySupplierId(Long supplierId){
        return apiProductInfoMapper.selectProductBySupplierId(supplierId);
    }

    /**
     * 根据商品名称查询商品信息
     * @param productName
     * @return
     */
    public List<ProductInfo> selectProductByName(String productName){
        return apiProductInfoMapper.selectProductByName(productName);
    }

    @Autowired(required = false)
    private ProductPicInfoMapper productPicInfoMapper;

    @Value("${absoluteImgPath}")
    String absoluteImgPath;
    @Value("${sonImgPath}")
    String sonImgPath;
    public Map<String, String> uploadImg(MultipartFile[] file, ProductPicInfo productPicInfo) {
        Map<String,String> map = new HashMap<>();
        String path="";
        for (int i = 0; i < file.length; i++) {
            if (file[i].isEmpty()) {
                map.put("code", "500");
                map.put("msg", "图片不能为空");
                System.out.println("图片不能为空");
                return map;
            }

            String originalFilename = file[i].getOriginalFilename();
            //随机生成文件名
            String fileName = RandomUtils.random() + originalFilename;
            File dest = new File(absoluteImgPath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            String feedPicture = sonImgPath + fileName;
            try {
                file[i].transferTo(dest);
                path+=feedPicture+",";
            } catch (Exception e) {
                map.put("ERROR", e.getMessage());
                return  map;
            }
        }

        try {
            productPicInfo.setPicUrl(path);
            productPicInfoMapper.insertProductPicInfo(productPicInfo);
            map.put("OK", "200");
            return map;
        }
        catch (Exception e){
            map.put("ERROR",  e.getMessage());
            return map;
        }
    }

    /**
     * 根据商品Id查询商品的规格信息
     * @param userId
     * @return
     */
    public List<ProductLabel> selectProductLableByProId(Long userId){
        return apiProductInfoMapper.selectProductLableByProId(userId);
    }

    /**
     * 根据规格Id查询商品的规格信息
     * @param productLabelId
     * @return
     */
    public ProductLabel selectProductLableByLableId(Long productLabelId){
        return apiProductInfoMapper.selectProductLableByLableId(productLabelId);
    }

    /**
     * 查询商家优惠券列表
     * @param supplierId
     * @return
     */
    public List<PreferentialCard> selectSupplierCoupon(Long supplierId){
        return apiProductInfoMapper.selectSupplierCoupon(supplierId);
    }

    /**
     * 查询店铺加入的平台优惠活动券
     * @param supplierId
     * @return
     */
    public PlatformCoupon selectSupplierPlatformCoupon(Long supplierId){
        SupplierInfo supplier = apiProductInfoMapper.getSupplierById(supplierId);
        System.out.println("*******************************************aaaaa*************"+supplier);
        return apiProductInfoMapper.selectSupplierPlatformCoupon(supplier.getPlatformId().longValue());
    }

    /**
     * 根据商品的id查询规格的图片
     * @param productId
     * @return
     */
    @Override
    public List<PpiUrlVo> selectPpiUrl(Integer productId) {
        return apiProductInfoMapper.selectPpiUrl(productId);
    }


    /**
     * 商家入驻
     * @param supplierInfo
     * @return
     */
    public int installSupplier(SupplierInfo supplierInfo){
        SysUser user = new SysUser();
        user.setUserName(supplierInfo.getPhoneNumber());
        user.setNickName(supplierInfo.getShopsName());
        user.setPhonenumber(supplierInfo.getPhoneNumber());
        user.setSex("2");
        user.setStatus("1");
        Long postIds[]= new Long[1];
        postIds[0] = Long.valueOf(104);
        user.setPostIds(postIds);
        Long roleIds[]= new Long[1];
        if(supplierInfo.getSupplierTypeform() == 1){
            roleIds[0] = Long.valueOf(5);
        }else{
            roleIds[0] = Long.valueOf(3);
        }
        user.setRoleIds(roleIds);
        user.setCreateBy(supplierInfo.getSupplierName());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(supplierInfo.getPhoneNumber()));
        userService.insertUser(user);
        System.out.println("------------------------------user:"+user);
        supplierInfo.setCustomerId(user.getUserId());
        supplierInfo.setSupplierStatus("1");
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i=0;i<8;i++){
            stringBuilder.append(random.nextInt(10));
        }
        String num =stringBuilder.toString();
        supplierInfo.setSupplierCode(num);
        return apiProductInfoMapper.installSupplier(supplierInfo);
    }

    /**
     * 根据负责人手机号查询店铺信息
     * @param supplierInfo
     * @return
     */
    public int checkSupplierPhone(SupplierInfo supplierInfo){
        return apiProductInfoMapper.checkSupplierPhone(supplierInfo);
    }

    @Override
    public  List<ProductInfo> selectSecondAll() {
        return apiProductInfoMapper.selectSecondAll();
    }

    @Override
    public  List<ProductInfo> selectProductByCateGoryList() {
        return apiProductInfoMapper.selectProductByCateGoryList();
    }


}
